//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Web;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.EventQueue;
namespace DotNetNuke.Entities.Modules
{
	public class EventMessageProcessor : DotNetNuke.Services.EventQueue.EventMessageProcessorBase
	{
		private void ImportModule(EventMessage message)
		{
			try {
				string BusinessControllerClass = message.Attributes["BusinessControllerClass"];
				object objController = Framework.Reflection.CreateObject(BusinessControllerClass, "");
				if (objController is IPortable) {
					int ModuleId = Convert.ToInt32(message.Attributes["ModuleId"]);
                    string Content = HttpUtility.HtmlDecode(message.Attributes["Content"]);
					string Version = message.Attributes["Version"];
					int UserID = Convert.ToInt32(message.Attributes["UserId"]);
					((IPortable)objController).ImportModule(ModuleId, Content, Version, UserID);
					ModuleController.SynchronizeModule(ModuleId);
				}
			} catch (Exception exc) {
				DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
			}
		}
		private void UpgradeModule(EventMessage message)
		{
			try {
				string BusinessControllerClass = message.Attributes["BusinessControllerClass"];
				object objController = Framework.Reflection.CreateObject(BusinessControllerClass, "");
				Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
				Services.Log.EventLog.LogInfo objEventLogInfo;
				if (objController is IUpgradeable) {
					string[] UpgradeVersions = message.Attributes["UpgradeVersionsList"].ToString().Split(',');
					foreach (string Version in UpgradeVersions) {
						string Results = ((IUpgradeable)objController).UpgradeModule(Version);
						objEventLogInfo = new Services.Log.EventLog.LogInfo();
						objEventLogInfo.AddProperty("Module Upgraded", BusinessControllerClass);
						objEventLogInfo.AddProperty("Version", Version);
						if (!string.IsNullOrEmpty(Results)) {
							objEventLogInfo.AddProperty("Results", Results);
						}
						objEventLogInfo.LogTypeKey = Services.Log.EventLog.EventLogController.EventLogType.MODULE_UPDATED.ToString();
						objEventLog.AddLog(objEventLogInfo);
					}
				}
				UpdateSupportedFeatures(objController, Convert.ToInt32(message.Attributes["DesktopModuleId"]));
			} catch (Exception exc) {
				DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
			}
		}
		private void UpdateSupportedFeatures(EventMessage message)
		{
			string BusinessControllerClass = message.Attributes["BusinessControllerClass"];
			object objController = Framework.Reflection.CreateObject(BusinessControllerClass, "");
			UpdateSupportedFeatures(objController, Convert.ToInt32(message.Attributes["DesktopModuleId"]));
		}
		private void UpdateSupportedFeatures(object objController, int desktopModuleId)
		{
			try {
				DesktopModuleInfo oDesktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger);
				if ((oDesktopModule != null)) {
					oDesktopModule.SupportedFeatures = 0;
					oDesktopModule.IsPortable = (objController is IPortable);
					oDesktopModule.IsSearchable = (objController is ISearchable);
					oDesktopModule.IsUpgradeable = (objController is IUpgradeable);
					DesktopModuleController.SaveDesktopModule(oDesktopModule, false, true);
				}
			} catch (Exception exc) {
				DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
			}
		}

        public static void CreateImportModuleMessage(ModuleInfo objModule, string content, string version, int userID)
        {
            EventMessage oAppStartMessage = new EventMessage();
            oAppStartMessage.Priority = MessagePriority.High;
            oAppStartMessage.ExpirationDate = DateTime.Now.AddYears(-1);
            oAppStartMessage.SentDate = System.DateTime.Now;
            oAppStartMessage.Body = "";
            oAppStartMessage.ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke";
            oAppStartMessage.ProcessorCommand = "ImportModule";

            //Add custom Attributes for this message
            oAppStartMessage.Attributes.Add("BusinessControllerClass", objModule.DesktopModule.BusinessControllerClass);
            oAppStartMessage.Attributes.Add("ModuleId", objModule.ModuleID.ToString());
            oAppStartMessage.Attributes.Add("Content", content);
            oAppStartMessage.Attributes.Add("Version", version);
            oAppStartMessage.Attributes.Add("UserID", userID.ToString());

            //send it to occur on next App_Start Event
            EventQueueController.SendMessage(oAppStartMessage, "Application_Start_FirstRequest");
        }

	    public override bool ProcessMessage(EventMessage message)
		{
			try {
				switch (message.ProcessorCommand) {
					case "UpdateSupportedFeatures":
						UpdateSupportedFeatures(message);
						break;
					case "UpgradeModule":
						UpgradeModule(message);
						break;
					case "ImportModule":
						ImportModule(message);
						break;
					default:
						break;
				}
			} catch (Exception ex) {
				message.ExceptionMessage = ex.Message;
				return false;
			}
			return true;
		}
	}
}
